package com.bcfrj.shop.controller;

import com.bcfrj.shop.pojo.Advert;
import com.bcfrj.shop.service.impl.AdvertServiceImpl;
import com.bcfrj.shop.utils.FileUtils;
import com.bcfrj.shop.utils.Result;
import org.apache.tomcat.jni.File;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/advert")
public class AdvertController {
    @Autowired
    private AdvertServiceImpl advertService;
    @GetMapping("/advertList")
    public Result advertList(){
        List<Advert> advertList = advertService.queryAdvertAll();
        if (advertList != null) {
            return Result.ok(advertList);
        } else {
            return Result.fail("列表为空");
        }
    }

    @GetMapping("/advert")
    public Result advert(Integer id){
        Advert advert = advertService.queryAdvertById(id);
        if (advert != null) {
            return Result.ok(advert);
        } else {
            return Result.fail("广告不存在");
        }
    }

    @PostMapping("/addAdvert")
    public Result addAdvert(MultipartFile uploadFile,Advert advert, HttpServletRequest request){
        System.out.println(advert);
        String advertImage = "";

        if (uploadFile != null) {
            advertImage = FileUtils.saveFile(uploadFile,request);
        }

        advert.setAdvert_image(advertImage);

        int rows = advertService.insertAdvert(advert);

        if (rows > 0 ) {
            return Result.ok("添加成功");
        }
        else {
            return Result.fail("添加失败");
        }
    }

    @PostMapping("/updateAdvert")
    public Result updateAdvert(MultipartFile uploadFile,Advert advert, HttpServletRequest request){
        if (uploadFile == null && advert.getAdvert_image() != null && advert.getAdvert_id()!=null) {
            Integer rows = advertService.updateAdvert(advert);
            if (rows > 0) {
                return Result.ok("修改成功");
            }else{
                return Result.ok("修改失败");
            }
        }
        else {
            String advertImage = "";
            if (uploadFile != null) {
                advertImage = FileUtils.saveFile(uploadFile,request);
            }
            else {
                return Result.fail("请上传图片");
            }

            advert.setAdvert_image(advertImage);
            int rows = advertService.updateAdvert(advert);

            if (rows > 0) {
                return Result.ok("修改成功");
            }else{
                return Result.fail("修改失败");
            }

        }
    }

    @PostMapping("/deleteAdvert")
    public Result deleteAdvert(Integer id){
        int rows = advertService.deleteAdvert(id);
        if (rows > 0) {
            return Result.ok("删除成功");
        }else{
            return Result.fail("删除失败");
        }
    }
}
